import { login, logout, getInfo } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: null
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    if (token) {
      setToken(token)
    } else {
      removeToken()
    }
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
  }
}

const getters = {
  token: state => state.token
}

const actions = {
  async login({ commit }, userInfo) {
    try {
      const { token } = await login(userInfo)
      commit('SET_TOKEN', token)
      return token
    } catch (error) {
      throw error
    }
  },

  async logout({ commit }) {
    try {
      await logout()
      commit('SET_TOKEN', null)
      commit('SET_USER_INFO', null)
    } catch (error) {
      throw error
    }
  },

  async getUserInfo({ commit }) {
    try {
      const userInfo = await getInfo()
      commit('SET_USER_INFO', userInfo)
      return userInfo
    } catch (error) {
      throw error
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
} 